#include"SList.h"
STNode* STBuyNode(SLTDatatype val) {
	STNode* newnode = (STNode*)malloc(sizeof(STNode));
	if (newnode == NULL) {
		perror("malloc fail!!");
		exit(1);
	}
	newnode->next = NULL;
	newnode->val = val;
	return newnode;
}
void STPushBack(STNode** pphead, SLTDatatype val) {
	assert(pphead);
	STNode* newnode = STBuyNode(val);
	if (*pphead == NULL) {
		*pphead = newnode;
	}
	else {
		STNode* pcur = *pphead;
		while (pcur->next) {
			pcur = pcur->next;
		}
		pcur->next = newnode;
	}
}
STNode* STPrint(STNode* phead) {
	STNode* pcur = phead;
	while (pcur) {
		printf("%d -> ", pcur->val);
		pcur = pcur->next;
	}
	printf("NULL\n");
}
void STPushFront(STNode** pphead, SLTDatatype val) {
	assert(pphead);
	STNode* newnode = STBuyNode(val);
	newnode->next = *pphead;
	*pphead = newnode;
}
void STPopBack(STNode** pphead) {
	assert(pphead && *pphead);
	if ((*pphead)->next == NULL) {
		free(*pphead);
		*pphead = NULL;
	}
	else {
		STNode* pcur = *pphead;
		STNode* prev = NULL;
		while (pcur->next) {
			prev = pcur;
			pcur = pcur->next;
		}
		free(pcur);
		pcur = NULL;
		prev->next = NULL;
	}
}
void STPopFront(STNode** pphead) {
	assert(pphead && *pphead);
	STNode* del = *pphead;
	*pphead = (*pphead)->next;
	free(del);
}
STNode* STFind(STNode* phead,SLTDatatype x) {
	assert(phead);
	STNode* pcur = phead;
	while (pcur) {
		if (pcur->val == x) {
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}
void STInsert(STNode** pphead, STNode* pos,SLTDatatype x) {
	assert(pphead && pos);
	if (pos == *pphead) {
		STPushFront(pphead,x);
	}
	else {
		STNode* newnode = STBuyNode(x);
		STNode* pcur = *pphead;
		while (pcur->next != pos) {
			pcur = pcur->next;
		}
		newnode->next = pos;
		pcur->next = newnode;
	}
}

void STInsertAfter(STNode* pos, SLTDatatype x) {
	assert(pos);
	STNode* newnode = STBuyNode(x);
	newnode->next = pos->next;
	pos->next = newnode;
}

void STErase(STNode** pphead, STNode* pos) {
	assert(pphead && *pphead);
	assert(pos);
	if (pos==*pphead) {
		STPopFront(pphead);
	}
	else {
		STNode* pcur = *pphead;
		while (pcur->next != pos) {
			pcur = pcur->next;
		}
		pcur->next = pos->next;
		free(pos);
		pos = NULL;
	}
}

void STEraseAfter(STNode** pphead,STNode* pos) {
	assert(pos&&pos->next);
	assert(pphead && *pphead);
	STNode* del = pos->next;
	pos->next = del->next;
	free(del);
	del = NULL;
}

void STDestroy(STNode** pphead) {
	assert(pphead);
	STNode* pcur = *pphead;
	STNode* next = (*pphead)->next;
	while (pcur) {
		free(pcur);
		pcur = next;
		if(next)
			next = next->next;
	}
	*pphead = NULL;
}
